import React, { useState, useEffect } from 'react';
import { Zap, Database, BarChart3, RefreshCw, TrendingUp } from 'lucide-react';
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from 'recharts';
import { monitorApi } from '../../services/monitor';
import type { ThroughputMetrics } from '../../types/monitor';

interface ThroughputMonitorProps {
  refreshInterval?: number;
}

const ThroughputMonitor: React.FC<ThroughputMonitorProps> = ({
  refreshInterval = 30000
}) => {
  const [loading, setLoading] = useState(false);
  const [metrics, setMetrics] = useState<ThroughputMetrics | null>(null);
  const [error, setError] = useState<string | null>(null);

  // 获取吞吐量指标
  const fetchThroughputMetrics = async () => {
    try {
      setLoading(true);
      setError(null);
      const response = await monitorApi.getThroughputMetrics();
      if (response.success) {
        setMetrics(response.data);
      }
    } catch (error) {
      console.error('获取吞吐量指标失败:', error);
      setError('获取吞吐量指标失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchThroughputMetrics();
    const interval = setInterval(fetchThroughputMetrics, refreshInterval);
    return () => clearInterval(interval);
  }, [refreshInterval]);

  // 格式化字节数
  const formatBytes = (bytes: number) => {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  };

  // 准备图表数据
  const prepareChartData = () => {
    if (!metrics?.topics) return [];
    
    return Object.entries(metrics.topics)
      .filter(([topicName]) => !topicName.startsWith('__'))
      .map(([topicName, topicData]) => ({
        topic: topicName,
        rate: topicData.production_rate_per_minute,
        bytes: topicData.estimated_bytes_per_minute / 1024 / 1024 // 转换为MB
      }))
      .sort((a, b) => b.rate - a.rate)
      .slice(0, 10);
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500"></div>
        <span className="ml-2">加载中...</span>
      </div>
    );
  }

  if (error) {
    return (
      <div className="bg-red-50 border border-red-200 rounded-lg p-4">
        <div className="flex items-center">
          <TrendingUp className="w-5 h-5 text-red-500 mr-2" />
          <span className="text-red-700">{error}</span>
        </div>
      </div>
    );
  }

  if (!metrics) {
    return (
      <div className="bg-gray-50 border border-gray-200 rounded-lg p-4">
        <div className="text-center text-gray-500">暂无数据</div>
      </div>
    );
  }

  const chartData = prepareChartData();

  return (
    <div className="space-y-6">
      {/* 集群吞吐量概览 */}
      <div className="grid grid-cols-1 md:grid-cols-6 gap-4">
        <div
          className="bg-white rounded-lg shadow-sm border p-6 cursor-pointer hover:shadow-md transition-shadow"
          onClick={fetchThroughputMetrics}
        >
          <div className="flex items-center">
            <Zap className="w-8 h-8 text-blue-500 mr-3" />
            <div>
              <p className="text-sm font-medium text-gray-600">生产速率</p>
              <p className="text-2xl font-bold text-gray-900">
                {metrics.cluster_throughput.total_production_rate_per_minute.toFixed(1)}
              </p>
              <p className="text-xs text-gray-500">msg/min</p>
            </div>
          </div>
        </div>

        <div
          className="bg-white rounded-lg shadow-sm border p-6 cursor-pointer hover:shadow-md transition-shadow"
          onClick={fetchThroughputMetrics}
        >
          <div className="flex items-center">
            <TrendingUp className="w-8 h-8 text-purple-500 mr-3" />
            <div>
              <p className="text-sm font-medium text-gray-600">消费速率</p>
              <p className="text-2xl font-bold text-gray-900">
                {metrics.cluster_throughput.total_consumption_rate_per_minute.toFixed(1)}
              </p>
              <p className="text-xs text-gray-500">msg/min</p>
            </div>
          </div>
        </div>

        <div
          className="bg-white rounded-lg shadow-sm border p-6 cursor-pointer hover:shadow-md transition-shadow"
          onClick={fetchThroughputMetrics}
        >
          <div className="flex items-center">
            <Database className="w-8 h-8 text-green-500 mr-3" />
            <div>
              <p className="text-sm font-medium text-gray-600">字节速率</p>
              <p className="text-2xl font-bold text-gray-900">
                {formatBytes(metrics.cluster_throughput.total_bytes_per_minute)}
              </p>
              <p className="text-xs text-gray-500">/min</p>
            </div>
          </div>
        </div>

        <div
          className="bg-white rounded-lg shadow-sm border p-6 cursor-pointer hover:shadow-md transition-shadow"
          onClick={fetchThroughputMetrics}
        >
          <div className="flex items-center">
            <BarChart3 className="w-8 h-8 text-orange-500 mr-3" />
            <div>
              <p className="text-sm font-medium text-gray-600">总分区数</p>
              <p className="text-2xl font-bold text-gray-900">
                {(metrics.cluster_throughput.total_partitions || 0).toLocaleString()}
              </p>
              <p className="text-xs text-gray-500">个</p>
            </div>
          </div>
        </div>

        <div
          className="bg-white rounded-lg shadow-sm border p-6 cursor-pointer hover:shadow-md transition-shadow"
          onClick={fetchThroughputMetrics}
        >
          <div className="flex items-center">
            <BarChart3 className="w-8 h-8 text-yellow-500 mr-3" />
            <div>
              <p className="text-sm font-medium text-gray-600">活跃Topic数</p>
              <p className="text-2xl font-bold text-gray-900">
                {metrics.cluster_throughput.active_topics}
              </p>
              <p className="text-xs text-gray-500">/ {Object.keys(metrics.topics).length}</p>
            </div>
          </div>
        </div>

        <div
          className="bg-white rounded-lg shadow-sm border p-6 cursor-pointer hover:shadow-md transition-shadow"
          onClick={fetchThroughputMetrics}
        >
          <div className="flex items-center">
            <RefreshCw
              className={`w-8 h-8 text-blue-500 mr-3 ${loading ? 'animate-spin' : ''}`}
            />
            <div>
              <p className="text-sm font-medium text-gray-600">点击刷新</p>
              <p className="text-sm text-gray-500">刷新吞吐量数据</p>
            </div>
          </div>
        </div>
      </div>

      {/* Topic生产速率排行 */}
      <div className="bg-white rounded-lg shadow-sm border">
        <div className="px-6 py-4 border-b border-gray-200">
          <h3 className="text-lg font-medium text-gray-900">Topic生产速率排行</h3>
        </div>
        <div className="p-6">
          {chartData.length === 0 ? (
            <div className="text-center text-gray-500 py-8">暂无活跃Topic</div>
          ) : (
            <ResponsiveContainer width="100%" height={300}>
              <BarChart data={chartData}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis 
                  dataKey="topic" 
                  angle={-45}
                  textAnchor="end"
                  height={80}
                />
                <YAxis />
                <Tooltip 
                  formatter={(value, name) => [
                    name === 'rate' ? `${value} msg/min` : `${value.toFixed(2)} MB/min`,
                    name === 'rate' ? '生产速率' : '字节速率'
                  ]}
                />
                <Bar dataKey="rate" fill="#3b82f6" name="rate" />
              </BarChart>
            </ResponsiveContainer>
          )}
        </div>
      </div>

      {/* Topic详细列表 */}
      <div className="bg-white rounded-lg shadow-sm border">
        <div className="px-6 py-4 border-b border-gray-200">
          <h3 className="text-lg font-medium text-gray-900">Topic详细信息</h3>
        </div>
        <div className="p-6">
          {Object.keys(metrics.topics).length === 0 ? (
            <div className="text-center text-gray-500 py-8">暂无Topic</div>
          ) : (
            <div className="space-y-4">
              {Object.entries(metrics.topics)
                .filter(([topicName]) => !topicName.startsWith('__'))
                .map(([topicName, topicData]) => (
                <div key={topicName} className="border border-gray-200 rounded-lg p-4">
                  <div className="flex items-center justify-between">
                    <div className="flex items-center">
                      <Database className="w-5 h-5 text-gray-400 mr-2" />
                      <span className="font-medium">{topicName}</span>
                      <span className="ml-2 px-2 py-1 text-xs bg-blue-100 text-blue-800 rounded-full">
                        {topicData.partition_count} 分区
                      </span>
                    </div>
                    <div className="flex items-center space-x-4 text-sm text-gray-500">
                      <span>速率: {topicData.production_rate_per_minute.toFixed(1)} msg/min</span>
                      <span>字节: {formatBytes(topicData.estimated_bytes_per_minute)}/min</span>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default ThroughputMonitor;
